import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from 'fs';
import { basename, extname, join } from 'path';
import { commands, Uri, window, workspace } from 'vscode';
import { config, MessageFormat } from 'vscode-nls';

const localize = config({
	messageFormat: MessageFormat.file
})(__filename);

export default function add() {
	return commands.registerCommand('feidao.h5.page.add', async (uri: Uri) => {
		const path = uri.fsPath;
		const root = workspace.getWorkspaceFolder(uri).uri.fsPath;
		const folder = join(root, 'src-h5');
		const value = (() => {
			const stat = statSync(path);
			if (stat.isDirectory()) {
				return '';
			} else if (stat.isFile()) {
				if (extname(path) === '.html') {
					return basename(path, '.html');
				}
			}
		})();
		const pages = readdirSync(join(root, 'pages')).map((_p) => {
			return _p.substring(0, _p.lastIndexOf('.'));
		});
		const has_pages = readdirSync(join(root, 'src-h5'));
		const selects = pages.filter((_f) => {
			return has_pages.indexOf(_f) === -1;
		}).sort();
		selects.unshift(localize(3));
		if (value) {
			selects.splice(selects.indexOf(value), 1);
			selects.unshift(value);
		}
		const name = await (async () => {
			const pick = await window.showQuickPick(selects, {
				canPickMany: false,
				placeHolder: localize(0)
			});
			if (pick === localize(3)) {
				return await window.showInputBox({
					placeHolder: localize(0),
					value: '',
					validateInput(val) {
						const p_path = join(folder, val);
						if (existsSync(p_path)) {
							return localize(2);
						} else {
							return null;
						}
					}
				});
			} else {
				return pick;
			}
		})();
		if (has_pages.indexOf(name) !== -1) {
			window.showWarningMessage(localize(2));
			return;
		}
		if (name) {
			if (!existsSync(folder)) {
				mkdirSync(folder);
			}
			const p_path = join(folder, name);
			mkdirSync(p_path);
			// create n
			create_ns(p_path);
			create_na(p_path);
			create_html(p_path);
			create_n(p_path, name);
			// create b
			create_s(p_path);
			create_b(p_path);
			await workspace.saveAll();
			window.showInformationMessage(localize(1));
			window.showTextDocument(Uri.file(join(p_path, 'b.ts')));
		}
	});
}

function create_b(path: string) {
	const tpl = `import init from '@feidao/web/framework/browser/d/page';

import s from './s';

/// FEIDAO IMPCOMPONENTS BEGIN

/// FEIDAO IMPCOMPONENTS END


/// FEIDAO IMPACTIONS BEGIN

/// FEIDAO IMPACTIONS END

(() => {
	/// FEIDAO ACTIONS BEGIN

	const actions = {};

	/// FEIDAO ACTIONS END

	init(s, actions
		/// FEIDAO COMPONENTS BEGIN

		/// FEIDAO COMPONENTS END
	);
})();

`;
	writeFileSync(join(path, 'b.ts'), tpl);
}

function create_s(path: string) {
	const tpl = `export default {
};

`;
	writeFileSync(join(path, 's.ts'), tpl);
}

function create_html(path: string) {
	const tpl = `import { parse } from 'node-html-parser';

const html = \`
\`;

export default parse(html);

`;
	writeFileSync(join(path, 'html.ts'), tpl);
}

function create_na(path: string) {
	const tpl = `import { IFeidaoAiNodejsPage } from '@feidao/web/interfaces';

export default async function na001(fd: IFeidaoAiNodejsPage, ...args: any[]) {
	// todo
}
`;
	writeFileSync(join(path, 'na001.ts'), tpl);
}

function create_ns(path: string) {
	const tpl = `export default {
	'fd-events-server-check': 'na001'
};
`;
	writeFileSync(join(path, 'ns.ts'), tpl);
}

function create_n(path: string, page: string) {
	const tpl = `import { ICommonParams, IHeaders } from '@feidao/service/interfaces';
import html from './html';
import s from './ns';

import init from '@feidao/web/framework/nodejs/d/page';

/// FEIDAO IMPCOMPONENTS BEGIN

/// FEIDAO IMPCOMPONENTS END


/// FEIDAO IMPACTIONS BEGIN

/// FEIDAO IMPACTIONS END

export default async function main(url: string, msg: ICommonParams, headers: IHeaders) {

	/// FEIDAO ACTIONS BEGIN

	const actions = {};

	/// FEIDAO ACTIONS END


	const res = await init(html, url, msg, headers, s, actions
		/// FEIDAO COMPONENTS BEGIN

		/// FEIDAO COMPONENTS END
	);

	const html_str = \`<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="renderer" content="webkit">
		<title></title>
		<link inline rel="stylesheet" type="text/css" href="./css/iconfont-h5.css">
		<link inline href="https://cdn.jsdelivr.net/npm/feidao-css/feidao.css" type="text/css" rel="stylesheet">
		<link inline rel="stylesheet" type="text/css" href="./css/daokes-h5.css">
		<script src="https://cdn.jsdelivr.net/npm/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
		<script src="./js/feidao.js"></script>
		<script type="text/javascript">
			window.addEventListener('WebComponentsReady', function () {
				var t = document.createElement('script');
				t.src = './js/${page}.js';
				document.head.appendChild(t);
			});
		</script>
	</head>
	<body>
	$\{html.toString()\}
	</body>
</html>
	\`;
	const html_obj = { data: html_str };
	if (typeof res === 'object' && Object.keys(res).length > 0) {
		const result = Object.assign({}, html_obj, res);
		return result;
	}
	return html_obj;
}
`;
	writeFileSync(join(path, 'n.ts'), tpl);
}
